<script setup lang="ts">
import { h, onMounted, ref } from 'vue'
import { reqDeleteUser, reqDeleteUserBatch, reqUserList } from '@/api/user'
import { ElMessage, ElMessageBox } from 'element-plus'
import { OPERATION_TYPE } from '@/api/type.ts'
import UserForm from '@/views/acl/user/UserForm.vue'
import UserRoleForm from '@/views/acl/user/UserRoleForm.vue'
import type { Action } from 'element-plus'
import type { User } from '@/api/user/type.ts'

// 搜索关键字
const keyword = ref<string>('')
let useKeyword: string = ''

// 分页
const currentPage = ref<number>(1)
const pageSize = ref<number>(10)
const total = ref<number>(0)

// 表格展示的用户list
const userList = ref<User[]>([])
// 表格选中的用户list
const selectedUserList = ref<User[]>([])
const userFomRef = ref<any>()
const userRoleFomRef = ref<any>()

const operate = ref<OPERATION_TYPE>(OPERATION_TYPE.ADD)

const getUserList = async (page: number = currentPage.value, keyword = '') => {
  currentPage.value = page
  try {
    const { code, data, message } = await reqUserList(
      page,
      pageSize.value,
      keyword,
    )
    if (code == 200) {
      userList.value = data?.records
      total.value = data?.total
    } else {
      ElMessage.error(message)
    }
  } catch (err: any) {
    ElMessage.error(err?.message)
  }
}

const handleSelectionChange = (val: User[]) => {
  selectedUserList.value = val
}

const onSearch = () => {
  useKeyword = keyword.value
  getUserList(1, useKeyword)
}

const onSearchReset = () => {
  keyword.value = ''
  useKeyword = ''
  getUserList(1, useKeyword)
}

const onAddUser = () => {
  operate.value = OPERATION_TYPE.ADD
  userFomRef.value.setShow(true)
}

const onUpdateUser = (row: User) => {
  operate.value = OPERATION_TYPE.UPDATE
  userFomRef.value.setUserForm(row)
  userFomRef.value.setShow(true)
}

const onAssignRole = (row: User) => {
  userRoleFomRef.value.initRole(row)
}

const onDeleteUser = async (row: User) => {
  try {
    const { code, message } = await reqDeleteUser(row?.id as number)
    if (code == 200) {
      ElMessage.success('删除成功')
      await getUserList()
    } else {
      ElMessage.error(message)
    }
  } catch (err: any) {
    ElMessage.error(err?.message)
  }
}

const deleteUserBatch = async () => {
  const idList = selectedUserList.value.map((user) => {
    return user?.id
  })
  try {
    const { code, message } = await reqDeleteUserBatch(idList as number[])
    if (code == 200) {
      ElMessage.success('批量删除成功')
      await getUserList()
    } else {
      ElMessage.error(message)
    }
  } catch (err: any) {
    ElMessage.error(err?.message)
  }
}

const onDeleteUserBatch = () => {
  //@ts-expect-error ignore
  let userStr = selectedUserList.value.reduce((prev, cur, index) => {
    if (index == 1) {
      return prev.username + ', ' + cur.username
    }
    return prev + ', ' + cur.username
  })
  ElMessageBox.confirm(
    () =>
      h('p', null, [
        h('div', null, `确认删除${selectedUserList.value.length}个用户：`),
        h(
          'ol',
          null,
          selectedUserList.value.map((user) => {
            return h(
              'li',
              { style: { color: 'var(--el-color-danger)' } },
              user?.username,
            )
          }),
        ),
      ]),
    '批量删除用户',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      callback: (action: Action) => {
        if (action == 'confirm') {
          deleteUserBatch()
        }
      },
    },
  )
}

const onPageChange = () => {
  keyword.value = useKeyword
  getUserList(currentPage.value, useKeyword)
}

onMounted(() => {
  getUserList()
})
</script>

<template>
  <div>
    <el-card>
      <el-form :inline="true">
        <el-form-item label="用户名">
          <el-input v-model="keyword" placeholder="请输入用户名"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSearch">搜索</el-button>
          <el-button @click="onSearchReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <el-card>
      <el-button
        type="primary"
        icon="Plus"
        @click="onAddUser"
        v-has="'btn.User.add'"
      >
        添加用户
      </el-button>
      <el-button
        type="danger"
        :disabled="selectedUserList.length < 1"
        icon="Delete"
        @click="onDeleteUserBatch"
      >
        批量删除用户
      </el-button>
      <!-- 用户列表 -->
      <el-table
        :data="userList"
        @selection-change="handleSelectionChange"
        border
      >
        <el-table-column fixed type="selection"></el-table-column>
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column prop="id" label="id" width="80"></el-table-column>
        <el-table-column
          prop="name"
          label="用户姓名"
          width="180"
        ></el-table-column>
        <el-table-column
          prop="username"
          label="用户名称"
          width="180"
        ></el-table-column>
        <el-table-column label="用户角色" min-width="180">
          <template #default="{ row }">
            <el-tag
              v-for="(item, index) in row.roleName.split(',')"
              :key="index"
              :type="item ? '' : 'info'"
            >
              {{ item ? item : '暂无角色' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          prop="createTime"
          label="创建时间"
          width="100"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column
          prop="updateTime"
          label="更新时间"
          width="100"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column fixed="right" prop="" label="操作" width="300">
          <template #default="{ row }">
            <el-button
              type="primary"
              size="small"
              icon="User"
              @click="onAssignRole(row)"
            >
              分配角色
            </el-button>
            <el-button
              type="primary"
              size="small"
              icon="Edit"
              @click="onUpdateUser(row)"
            >
              编辑
            </el-button>
            <el-popconfirm
              :title="`确认删除用户：${row?.username}？`"
              @confirm="onDeleteUser(row)"
              confirm-button-text="确认"
              cancel-button-text="取消"
              width="200"
            >
              <template #reference>
                <el-button type="danger" size="small" icon="Delete">
                  删除
                </el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[2, 5, 10, 15]"
        :total="total"
        :small="true"
        :background="true"
        layout="prev, pager, next, jumper, ->, total, sizes"
        @change="onPageChange"
      ></el-pagination>
    </el-card>
    <UserForm
      ref="userFomRef"
      :operate="operate"
      @get-user-list="getUserList"
    ></UserForm>
    <UserRoleForm
      ref="userRoleFomRef"
      @get-user-list="getUserList"
    ></UserRoleForm>
  </div>
</template>

<style scoped lang="scss"></style>
